// 连接到Socket.IO服务器
const socket = io();

// 获取DOM元素
const userName = document.getElementById('user-name');
const userDepartment = document.getElementById('user-department');
const userPosition = document.getElementById('user-position');
const currentStatus = document.getElementById('current-status');
const totalTasks = document.getElementById('total-tasks');
const pendingTasks = document.getElementById('pending-tasks');
const inProgressTasks = document.getElementById('in-progress-tasks');
const completedTasks = document.getElementById('completed-tasks');
const taskList = document.getElementById('task-list');
const updateTime = document.getElementById('update-time');

// 监听共享数据更新
socket.on('shared-data-update', (data) => {
    updateUI(data);
    updateUpdateTime();
});

// 更新UI
function updateUI(data) {
    // 更新用户信息
    if (data.userInfo) {
        userName.textContent = data.userInfo.name || '-';
        userDepartment.textContent = data.userInfo.department || '-';
        userPosition.textContent = data.userInfo.position || '-';
    }
    
    // 更新状态
    if (data.status) {
        currentStatus.textContent = data.status.name || '-';
        currentStatus.style.backgroundColor = data.status.color || '#6c757d';
    }
    
    // 更新任务列表
    if (data.tasks) {
        updateTaskList(data.tasks);
        updateTaskStats(data.tasks);
    }
}

// 更新任务列表
function updateTaskList(tasks) {
    taskList.innerHTML = '';
    
    if (!tasks || tasks.length === 0) {
        taskList.innerHTML = '<li class="no-tasks">暂无任务</li>';
        return;
    }
    
    tasks.forEach(task => {
        const taskItem = document.createElement('li');
        taskItem.className = `task-item ${task.status === 'completed' ? 'completed' : ''}`;
        
        // 优先级文本
        const priorityText = {
            'low': '低',
            'medium': '中',
            'high': '高'
        };
        
        // 状态文本
        const statusText = {
            'pending': '待办',
            'in-progress': '进行中',
            'completed': '已完成'
        };
        
        // 检查是否逾期
        let isOverdue = false;
        if (task.dueDate && task.status !== 'completed') {
            const dueDate = new Date(task.dueDate);
            const now = new Date();
            isOverdue = dueDate < now;
        }
        
        taskItem.innerHTML = `
            <div class="task-item-header">
                <div class="task-item-title ${task.status === 'completed' ? 'completed' : ''}">
                    ${task.title}
                </div>
                <div class="task-item-meta">
                    <span class="priority-badge priority-${task.priority}">
                        ${priorityText[task.priority]}
                    </span>
                    <span class="status-badge-small status-${task.status}">
                        ${statusText[task.status]}
                    </span>
                </div>
            </div>
            ${task.description ? `<div class="task-item-description">${task.description}</div>` : ''}
            ${task.dueDate ? `
                <div class="due-date ${isOverdue ? 'overdue' : ''}">
                    截止日期: ${new Date(task.dueDate).toLocaleDateString('zh-CN')}
                    ${isOverdue ? ' (已逾期)' : ''}
                </div>
            ` : ''}
            ${task.hours && task.hours > 0 ? `
                <div class="task-hours">
                    工时: ${task.hours} 小时
                </div>
            ` : ''}
        `;
        
        taskList.appendChild(taskItem);
    });
}

// 更新任务统计
function updateTaskStats(tasks) {
    totalTasks.textContent = tasks.length;
    
    const pendingCount = tasks.filter(t => t.status === 'pending').length;
    pendingTasks.textContent = pendingCount;
    
    const inProgressCount = tasks.filter(t => t.status === 'in-progress').length;
    inProgressTasks.textContent = inProgressCount;
    
    const completedCount = tasks.filter(t => t.status === 'completed').length;
    completedTasks.textContent = completedCount;
}

// 更新时间
function updateUpdateTime() {
    const now = new Date();
    updateTime.textContent = now.toLocaleString('zh-CN');
}

// 页面加载完成后请求数据
document.addEventListener('DOMContentLoaded', () => {
    socket.emit('request-data-update');
});

// 每30秒自动刷新数据
setInterval(() => {
    socket.emit('request-data-update');
}, 30000);